const jsonwebtoken = require('jsonwebtoken');
const User = require('../models/users');
const Topic = require('../models/topics');
const Question = require('../models/questionSchema');
const Answer = require('../models/answers');
const { secret } = require('../config');

class UsersCtl {
    async find(ctx) {
        //limit 第几个开始  skip跳过多少个取多少个  Math.max选最大的一项
        const { per_page = 10 } = ctx.query;
        const page = Math.max(ctx.query.page * 1, 1) - 1;
        const perPage = Math.max(per_page * 1, 1);
        ctx.body = await User.find({ name: new RegExp(ctx.query.q) }).limit(perPage).skip(page * perPage);
    }
    async findeId(ctx) {
        const { fields = '' } = ctx.query;
        const selectFields = fields.split(';').filter(f => f).map(f => '+' + f).join("");
        //filter(f => f)过滤空字段
        const populateStr = fields.split(';').filter(f => f).map(f => {
            if (f === 'employments') {
                return 'employments.company employments.job'
            }
            if (f === 'educations') {
                return 'educations.school educations.major'
            }
            return f;
        }).join(' ')
        const user = await User.findById(ctx.params.id).select(selectFields).populate(populateStr);
        if (!user) { ctx.throw(404, '用户不存在') }
        ctx.body = user;
    }
    //用户的权限
    async checkOwner(ctx, next) {
        if (ctx.params.id !== ctx.state.user._id) { ctx.throw(403, '没有权限对此用户进行操作'); }
        await next();
    }
    async create(ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: true },
            password: { type: 'string', required: true },
        })
        const { name } = ctx.request.body;
        const repeatedUser = await User.findOne({ name });//查询数据库中的name字段，用来验证唯一性
        if (repeatedUser) {
            ctx.throw(409, '用户已存在')
        }
        console.log(ctx.request.body)
        const user = await new User(ctx.request.body).save();
        ctx.body = await User.findOne({ name });
    }
    async update(ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: false },
            password: { type: 'string', required: false },
            avatar_url: { type: 'string', required: false },
            gender: { type: 'string', required: false },
            headline: { type: 'string', required: false },
            locations: { type: 'array', itemType: 'string', required: false },
            business: { type: 'string', required: false },
            employments: { type: 'array', itemType: 'object', required: false },
            educations: { type: 'array', itemType: 'object', required: false },
        })
        const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body);
        if (!user) { ctx.throw(404, '用户不存在') }
        ctx.body = user;
    }
    async del(ctx) {
        const user = await User.findByIdAndDelete(ctx.params.id);
        if (!user) { ctx.throw(404, '用户不存在') }
        ctx.status = 204;
    }
    //登录方法
    async login(ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: true },
            password: { type: 'string', required: true }
        })
        const user = await User.findOne(ctx.request.body);
        if (!user) { ctx.throw(401, '用户不存在') }
        const { _id, name } = user;
        const token = jsonwebtoken.sign({ _id, name }, secret, { expiresIn: '1d' });
        ctx.body = { token };
    }
    //关注取消粉丝
    //获取某个用户关注人的列表  
    async listFollowing(ctx) {
        const user = await User.findById(ctx.params.id).select('+following').populate('following');
        if (!user) { ctx.throw(401, '用户不存在') };
        ctx.body = user;
    }
    //获取粉丝列表
    async listFollower(ctx) {
        const user = await User.find({ following: ctx.params.id });//获取特定ID所有的用户
        ctx.body = user;
    }
    //检查用户存在与否的中间件
    async checkUserExist(ctx, next) {
        const user = await User.findById(ctx.params.id);
        console.log(user)
        if (!user) { ctx.throw(401, '用户不存在') }
        await next()
    }
    //关注某人
    async follow(ctx) {
        const me = await User.findById(ctx.state.user._id).select('+following');
        if (!me.following.map(id => id.toString()).includes(ctx.params.id)) {//数据库里没有这个id时就push进去
            me.following.push(ctx.params.id);
            me.save();
            ctx.status = 204;
        } else {
            ctx.throw(401, '您已关注该用户');
        }
    }
    //取消关注
    async unfollow(ctx) {
        const me = await User.findById(ctx.state.user._id).select('+following');
        const index = me.following.map(id => id.toString()).indexOf(ctx.params.id);//获取你关注人的索引
        if (index > -1) {//数据库里没有这个id时就push进去
            me.following.splice(index, 1);
            me.save();
            ctx.status = 204;
        } else {
            ctx.throw(401, '您还没关注该用户，请去关注');
        }
    }

    //检查话题存在与否的中间件
    async checkTopicExist(ctx, next) {
        const topic = await Topic.findById(ctx.params.id);
        if (!topic) { ctx.throw(401, '用户不存在') }
        await next()
    }

    //获取关注的话题列表
    async listFollowingTopics(ctx) {
        const user = await User.findById(ctx.params.id).select('+followingTopics').populate('followingTopics');
        if (!user) { ctx.throw(401, '用户不存在') };
        ctx.body = user.followingTopics;
    }

    //关注话题
    async followTopic(ctx) {
        const me = await User.findById(ctx.state.user._id).select('+followingTopics');
        if (!me.followingTopics.map(id => id.toString()).includes(ctx.params.id)) {//数据库里没有这个id时就push进去
            me.followingTopics.push(ctx.params.id);
            me.save();
            ctx.status = 204;
        } else {
            ctx.throw(401, '您已关注该用户');
        }
    }
    //取消关注话题
    async unfollowTopic(ctx) {
        const me = await User.findById(ctx.state.user._id).select('+followingTopics');
        const index = me.followingTopics.map(id => id.toString()).indexOf(ctx.params.id);//获取你关注人的索引
        if (index > -1) {//数据库里没有这个id时就push进去
            me.followingTopics.splice(index, 1);
            me.save();
            ctx.status = 204;
        } else {
            ctx.throw(401, '您还没关注该用户，请去关注');
        }
    }

    //查询用户的问题列表
    async listQuestions(ctx) {
        const questions = await Question.find({ questioner: ctx.params.id });
        ctx.body = questions;
    }

    //查询赞过的列表
    async listLikingAnswers(ctx) {
        const user = await User.findById(ctx.params.id).select('+likingAnswers').populate('likingAnswers');
        if (!user) { ctx.throw(401, '用户不存在') };
        ctx.body = user.likingAnswers;
    }

    //赞喜欢答案
    async likeAnswer(ctx) {
        const me = await User.findById(ctx.state.user._id).select('+likingAnswers');
        if (!me.likingAnswers.map(id => id.toString()).includes(ctx.params.id)) {//数据库里没有这个id时就push进去
            me.likingAnswers.push(ctx.params.id);
            me.save();
            await Answer.findByIdAndUpdate(ctx.params.id, { $inc: { coteCount: 1 } });
            ctx.status = 204;
        } else {
            ctx.throw(401, '您已关注该用户');
        }
    }

    //赞取消答案
    async unlikeAnswer(ctx) {
        const me = await User.findById(ctx.state.user._id).select('+likingAnswers');
        const index = me.likingAnswers.map(id => id.toString()).indexOf(ctx.params.id);//获取你关注人的索引
        if (index > -1) {//数据库里没有这个id时就push进去
            me.likingAnswers.splice(index, 1);
            me.save();
            await Answer.findByIdAndUpdate(ctx.params.id, { $inc: { coteCount: -1 } })
            ctx.status = 204;
        } else {
            ctx.throw(401, '您还没关注该用户，请去关注');
        }
    }

    //查询踩过的列表
    async listDisLikingAnswers(ctx) {
        const user = await User.findById(ctx.params.id).select('+dislikingAnswers').populate('dislikingAnswers');
        if (!user) { ctx.throw(401, '用户不存在') };
        ctx.body = user.dislikingAnswers;
    }

    //踩喜欢答案
    async dislikeAnswer(ctx) {
        const me = await User.findById(ctx.state.user._id).select('+dislikingAnswers');
        if (!me.dislikingAnswers.map(id => id.toString()).includes(ctx.params.id)) {//数据库里没有这个id时就push进去
            me.dislikingAnswers.push(ctx.params.id);
            me.save();
            ctx.status = 204;
        } else {
            ctx.throw(401, '您已关注该用户');
        }
    }

    //踩取消答案
    async undislikeAnswer(ctx) {
        const me = await User.findById(ctx.state.user._id).select('+dislikingAnswers');
        const index = me.dislikingAnswers.map(id => id.toString()).indexOf(ctx.params.id);//获取你关注人的索引
        if (index > -1) {//数据库里没有这个id时就push进去
            me.dislikingAnswers.splice(index, 1);
            me.save();
            ctx.status = 204;
        } else {
            ctx.throw(401, '您还没关注该用户，请去关注');
        }
    }
}

module.exports = new UsersCtl();